package nz.ac.massey.jfontview;

import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.util.Collection;
import java.util.Vector;

/**
 * A default implementation of MutableFont.
 * It is composed of a java.awt.Font which is updated with
 * a new instance whenever a property changes. 
 * @author Nathan C Jones
 * @version 0.1
 */
public class DefaultMutableFont implements MutableFont{
	
	/**
	 * The font which represents the current state of the mutable font.
	 */
	private Font font;
	
	/**
	 * The collection of all registered mutable font listeners.
	 */
	private Collection<MutableFontListener> listeners = new Vector<MutableFontListener>();
	
	/**
	 * Create a new default mutable font using the
	 * default font as the initialising font.
	 * @see getDefaultFont()
	 */
	public DefaultMutableFont() {
		this(getDefaultFont());
	}
	
	/**
	 * Create a  new mutable font based on the given font.
	 * @param font the font to base the new mutable font from.
	 */
	public DefaultMutableFont(Font font){
		this.font = font;
	}

	/**
	 * Get a default font.
	 * It has a font face equivalent to the first item in the available system fonts,
	 * a size of 12, and a plain style. 
	 * @return the default font.
	 */
	public static Font getDefaultFont(){
		String name = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()[0];
		return new Font(name,Font.PLAIN,12);
	}

	public void setFont(Font f){
		font = f;
		fireFontChanged();
	}

	public Font getFont(){
		return font;
	}

	public void setStyle(int style){
		//TODO check for valid font style
		font = font.deriveFont(style);
		fireFontChanged();
	}

	public int getStyle(){
		return font.getStyle();
	}

	public void setSize(int size){
		font = font.deriveFont((float)size);
		fireFontChanged();
	}

	public int getSize(){
		return font.getSize();
	}

	public void setName(String name){
		font = new Font(name,font.getStyle(),font.getSize());
		fireFontChanged();
	}

	public String getName(){
		return font.getName();
	}

	public void addMutableFontListener(MutableFontListener listener){
		listeners.add(listener);
	}

	public void removeMutableFontListener(MutableFontListener listener){
		listeners.remove(listener);
	}

	public void fireFontChanged(){
		for(MutableFontListener l:listeners){
			l.fontChanged();
		}
	}

}
